require.config({
	shim: {	　　　　　　
		"bootstrap": {	// bootstrap依赖jquery库
			deps: ['jquery'],
			exports: 'bootstrap'
		},
		'handlebars': {　　　　　　　　
			exports: 'Handlebars'　　　　　　
		}　　　　
	},
	paths: {　　　　　　
		//工具模块
		'less': 'tools/less.min',
		'jquery': 'tools/jquery.min',
		'bootstrap': 'tools/bootstrap.min',
		'handlebars': 'tools/handlebars',

		//配置模块
		'config': './config',
		"appConfig":"./appConfig",
		'showBigImg':'modules/showBigImg',
		'top_bar': 'modules/top_bar',
		'problem': 'modules/problem',
		'ask': 'modules/ask',
		'modal_template': 'modules/modal_template',
		'cookie': 'modules/cookie',
		'check_log': 'modules/check_log',
		'login': 'modules/login',
		'other_log': 'modules/login',
		'reg': 'modules/reg',
		'user': 'modules/user',　　
		'setCenterImgBox':'modules/setCenterImgBox',
		'studioProblem':'modules/studioProblem',
		'jquery.mousewheel':"modules/jquery.mousewheel"
	}
});
/************************************header***************************************/
//加载顶栏top_bar模块
require(['top_bar'], function(top_bar){
	top_bar();
});
/************************************content***************************************/
require(['jquery','handlebars','config','cookie','ask','showBigImg','studioProblem','jquery.mousewheel'], function ($,Handlebars,config,cookie,ask,showBigImg,studioProblem){

	var studioId,url,userId;
	url=window.location.search;
	studioId=url.substring(url.indexOf("=")+1);
	userId=cookie.getCookie("userId");
	$(document).ready(function(){
		//画室环境提问框
		$("#environment_tabs_con").on("click",".environment_tabs",function(){
			$(".environment_tabs").removeClass("active");
			$(this).addClass("active");
			var refer=$(this).data("refer");
			$(".environmentTabBody").removeClass("show");
			$(".environmentTabBody[data-refer="+refer+"]").addClass("show");
			if(refer==0){
				$(".environmentContainer").removeClass("whiteBg").addClass("blackBg");
				$("#closeEnvironmentModal").css({
					backgroundImage:"url('../../image/whiteClose.png')"
				});
			}else{
				$(".environmentContainer").removeClass("blackBg").addClass("whiteBg");
				$("#closeEnvironmentModal").css({
					backgroundImage:"url('../../image/blackClose.png')"
				});

				setScrollBar();

			}//切换背景
		});//切换
		$("#commentInput").hide();
		$(".commentActionBar").on("click","#commentBtn",function(){
			$("#commentInput").slideDown();
			$(this).attr("id","confirmCommentBtn").text("确定");
			$(".commentActionBar").append("<button id='cancelCommentBtn'class='btn btn-default'>取消</button>");
		});	
		$(".commentActionBar").on("click","#confirmCommentBtn",function(){
			var comment=$("#commentInput").val();
			userId=cookie.getCookie("userId");
			if(userId==""){
				alert("请先登录");
				return;
			}else{
				commentStudio(comment,studioId,userId,function(){
					getCommentsAboutStudio(0,-1,studioId);
					$("#commentInput").val("").slideUp();
					$("#confirmCommentBtn").attr("id","commentBtn").text("我要评论");
					$("#cancelCommentBtn").remove();
				});
			}

		});	
		$(".commentActionBar").on("click","#cancelCommentBtn",function(){
			$("#commentInput").val("").slideUp();
			$("#confirmCommentBtn").attr("id","commentBtn").text("我要评论");
			$(this).remove();
		});	

	});
	function handlebarsRender(tplSelector, destSelector, data) {
		//用jquery获取模板
		var source = $(tplSelector).html();
		//预编译模板
		var template = Handlebars.compile(source);
		//匹配json内容
		var html = template(data);
		//输入模板
		$(destSelector).html(html);
	}
	Handlebars.registerHelper("firstInRow",function(index,options){
		if(index%3==0){//每行3列
			return options.fn(this);
		}else{
			return options.inverse(this);
		}
	});//注册一个用于判断是否是某行的第一个item的helper

	Handlebars.registerHelper('if_empty', function(value, options){
		if(value == ''){
			return options.fn(this);
		}
		else{
			return options.inverse(this);
		}
	});	//定义helper，判断头像是否为空

	//获取基础数据
	function fetchStudioDataById(id){
		$.ajax({
			url:config.api.getStudioInfo[0].replace(/\<\w+\>/,id),
			type:config.api.getStudioInfo[1],
			data:{
				userId :userId
			},
			success:function(data){
				console.log(data);
				handlebarsRender("#basic-template",".contentContainer",data);
				//与基础页面相关的事件绑定应该放在这里
				$(".tabs").delegate("li","click",function(){
					var ref=$(this).data("ref");
					$(".tab-nav").removeClass("active");
					$(this).addClass("active");
					$(".tabs-body").removeClass("show").parent().find(".tabs-body[data-ref="+ref+"]").addClass("show");
				});
				$(".actionBtnGroup").on("click",".followStudioBtn",subscribeStudio);
				$(".actionBtnGroup").on("click",".unfollowStudioBtn",unfollowStudio);
				$("#fansLink").attr("href","studioFans.html?studioId="+id);
				$("#followLink").attr("href","studioFollows.html?studioId="+id);
				//环境弹窗前，抓取数据
				$("#viewEnvironment").on("click",function(){
					getCommentsAboutStudio(0,20,id);
					getEnvironmentPics(id);
				});
				ask(id);//提问相关事件
				studioProblem.getProblemList(0,-1,userId,null,id);//获取画室已提问
				studioProblem.clickZan();
				getStudioWorksById(id);
				getStudioRecruitById(id);
				getStudioVideosById(id);
				getStudioTeachersById(id);
			}
		});
	}
	//获取画室作品
	function getStudioWorksById(id){
		$.ajax({
			url:config.api.getStudioWorks[0].replace(/\<\w+\>/,id),
			type:config.api.getStudioWorks[1],
			success:function(data){
				handlebarsRender("#works-template","#works",data);
				$("#works").on("click",".pic_row_item",function(){
					var src=$(this).attr("src");
					showBigImg(src);
				});//点击看大图
				//将图片设置为居中
				var w=($("#works").width()-40)*0.33;
				$(".pic_row_itemWrapper").css({
					lineHeight:w+"px"
				}).find(".pic_row_item").css({
					maxHeight:w+"px",
					maxWidth:w+"px"
				});
				$(window).resize(function(){
					var w=($("#works").width()-40)*0.33;
					$(".pic_row_itemWrapper").css({
						lineHeight:w+"px"
					}).find(".pic_row_item").css({
						maxHeight:w+"px",
						maxWidth:w+"px"
					});
				});
			}
		});
	}
	//获取画室全部视频
	function getStudioVideosById(id){
		$.ajax({
			url:config.api.getStudioVideos[0].replace(/\<\w+\>/,id),
			type:config.api.getStudioVideos[1],
			success:function(data){
				console.log(data);
				handlebarsRender("#video-template","#videos",data);
				$(".videolist").delegate("li","click",function(){
					var videoId=$(this).data("videoid");
					getOneVideo(videoId);
				});
			}
		});
	}
	//获取某个视频详细信息
	function getOneVideo(videoId){
		$.ajax({
			url:config.api.getOneVideo[0].replace(/\<\w+\>/,videoId),
			type:config.api.getOneVideo[1],
			success:function(data){
				console.log(data);
				handlebarsRender("#videoModal-template","#videoModal",data);
				$(".closeBtn").on("click",function(){
					var player=document.getElementById("player");
					player.pause();
					//停止播放
				});
			}
		});
	}
	//获取画室招聘信息
	function getStudioRecruitById(id){
		$.ajax({
			url:config.api.getStudioRecruit[0].replace(/\<\w+\>/,id),
			type:config.api.getStudioRecruit[1],
			success:function(data){
				handlebarsRender("#recuitSection-template",".recruitBoard",data);

			}
		});
	}
	//获取画室教师
	function getStudioTeachersById(id){
		$.ajax({
			url:config.api.getStudioTeachers[0].replace(/\<\w+\>/,id),
			type:config.api.getStudioTeachers[1],
			success:function(data){
				console.log(data);
				handlebarsRender("#teacherList-template","#teachers",data);

			}
		});
	}
	function formatDate(timestamp){  
	              var dateObj=new Date(timestamp);   
	              var   year=dateObj.getYear()+1900;     
	              var   month=dateObj.getMonth()+1;     
	              var   date=dateObj.getDate();     
	              var   hour=dateObj.getHours();     
	              var   minute=dateObj.getMinutes();       
	              return   year+"-"+month+"-"+date+"   "+hour+":"+(minute<10?"0"+minute:minute);     
	}
	//获取画室评论
	function getCommentsAboutStudio(skip,total,id){
		$.ajax({
			url:config.api.getCommentsAboutStudio[0].replace(/\<\w+\>/,id),
			type:config.api.getCommentsAboutStudio[1],
			data:{
				skip:skip,
				total:total
			},
			success:function(data){
				console.log(data);
				data.studioComments.forEach(function(comment){
					comment.timestamp=formatDate(comment.timestamp);
				});	
				handlebarsRender("#comments-template",".commentsList",data);
				setScrollBar();	
			},
			error:function(){}
		});
	}
	//评论画室
	function commentStudio(content,studioId,userId,callback){
		$.ajax({
			url:config.api.commentStudio[0].replace(/\<\w+\>/,userId),
			type:config.api.commentStudio[1],
			data:{
				content:content,
				studioId:studioId
			},
			success:function(data){
				if(typeof callback=="function"){
					callback();
				}
			},
			error:function(){}
		});
	}
	//获取画室环境图片
	function getEnvironmentPics(id){
		$.ajax({
			url:config.api.getStudioEnvironment[0].replace(/\<\w+\>/,id),
			type:config.api.getStudioEnvironment[1],
			success:function(data){
				handlebarsRender("#carousel-template","#myCarousel",data);
				console.log(data);
			},
			error:function(){}
		});
	}
	//设置评论列表的滚动条样式 以及绑定事件
	function setScrollBar(){
		var listHeight=$(".commentsList").height();
		var pageHeight=417;//一屏能够展示的高度
		var scrollBarHeight=$("#scrollBar").height();
		var handleHeight;//把手的高度
		if(listHeight<417){
			$("#scrollBar").hide();
			handleHeight=0;
			$("#handle").height(handleHeight);//根据列表长度计算把手高度
		}else{
			$("#scrollBar").show();
			handleHeight=pageHeight*scrollBarHeight/listHeight;
			$("#handle").height(handleHeight);//根据列表长度计算把手高度
			var maxPos=scrollBarHeight-handleHeight;
			var pos_handle=0;
			var pos_list=0;
			$("#environmentModal>.modal-dialog").mousewheel(function(event, delta, deltaX, deltaY) {
			   var delta=deltaY*20;
			   pos_handle-=delta;
			   pos_list+=delta*listHeight/scrollBarHeight;
			   if(pos_handle<0){
			   	pos_handle=0;
			   }else if(pos_handle>maxPos){
			   	pos_handle=maxPos;
			   }//限制
			   if(pos_list<417-listHeight){
			   	pos_list=417-listHeight;
			   }else if(pos_list>0){
			   	pos_list=0;
			   }//限制
			   $("#handle").css({top:pos_handle+"px"});
			   $(".commentsList").css({top:pos_list+"px"});
			});

		}

	}
	//订阅该画室
	function subscribeStudio(){
		console.log("follow");
		//var studioId=
		//var userId=cookie.getCookie("userId");
		if(userId!=""){
			$.ajax({
				url:config.api.subscribeStudio[0].replace(/\<\w+\>/,userId),
				type:config.api.subscribeStudio[1],
				data:{
					studioId:studioId
				},
				success:function(){

					$(".followStudioBtn").removeClass("followStudioBtn")
										.addClass("unfollowStudioBtn")
										.text("取消关注");
				}
			});
		}else{
			alert("请先登录");
		}

	}
	//取关该画室
	function unfollowStudio(){
		console.log("unfollow");
		//var studioId=
		//var userId=cookie.getCookie("userId");
		if(userId!=""){
			$.ajax({
				url:config.api.unfollowStudio[0].replace(/\<\w+\>/,userId),
				type:config.api.unfollowStudio[1],
				data:{
					studioId:studioId
				},
				success:function(){

					$(".unfollowStudioBtn").removeClass("unfollowStudioBtn")
											.addClass("followStudioBtn")
											.text("关注");
				}
			});
		}else{
			alert("请先登录");
		}

	}
	fetchStudioDataById(studioId);

});
require(['less','bootstrap'],function(){
	console.log("less,bootstrap loaded");
});
